package com.ABdolphin.forum.controller;

import com.ABdolphin.forum.common.AppResult;
import com.ABdolphin.forum.common.ResultCode;
import com.ABdolphin.forum.config.AppConfig;
import com.ABdolphin.forum.exception.ApplicationException;
import com.ABdolphin.forum.model.Message;
import com.ABdolphin.forum.model.User;
import com.ABdolphin.forum.services.IMessageService;
import com.ABdolphin.forum.services.IUserService;
import com.ABdolphin.forum.services.impl.MessageServiceImpl;
import com.ABdolphin.forum.services.impl.UserServiceImpl;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/message")
@RestController
@Slf4j
@Tag(name = "Message")
public class MessageController {
    @Resource(type = MessageServiceImpl.class)
    private IMessageService messageService;

    @Resource(type = UserServiceImpl.class)
    private IUserService userService;


    @PostMapping("/send")
    @Operation(summary = "发送站内信")
    public AppResult send(HttpServletRequest request,
                          @Parameter(name = "receiveUserId",description = "接受者id")@RequestParam("receiveUserId") @NotNull Long receiveUserId,
                          @Parameter(name = "content",description = "内容")@RequestParam("content") @NotNull String content){
        User postUser = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        //是否禁言
        if (postUser.getState()==1){
            log.info(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        //不可以给自己发送消息
        if (postUser.getId().equals(receiveUserId)){
            log.info(ResultCode.FAILED_MESSAGE_TO_ONESELF.toString());
            return AppResult.fail(ResultCode.FAILED_MESSAGE_TO_ONESELF);
        }
        //是否存在接受者
        User receiveUser = userService.selectById(receiveUserId);
        if (receiveUser==null){
            log.info(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            return AppResult.fail(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        Message message = new Message();
        message.setPostUserId(postUser.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        messageService.create(message);
        return AppResult.success();

    }
    @GetMapping("/getUnreadCount")
    @Operation(summary = "获得未读站内信数量")
    public AppResult getUnreadCount (HttpServletRequest request){
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        Integer count = messageService.getUnReadCount(user.getId());
        return AppResult.success(count);
    }

    @GetMapping("/getAll")
    @Operation(summary = "获得站内信列表")
    public AppResult<List<Message>> getAll (HttpServletRequest request){
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        List<Message> messages = messageService.selectByReceiveUserId(user.getId());
        if (messages==null){
            messages=new ArrayList<>();
        }
        return AppResult.success(messages);
    }
    @PostMapping("/markRead")
    @Operation(summary = "修改站内信状态--已读")
    public AppResult markRead(HttpServletRequest request,
                              @Parameter(name = "id",description = "站内信id")@RequestParam("id")@NotNull Long id){
        Message message = messageService.selectById(id);
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        if (message==null||
                !user.getId().equals(message.getReceiveUserId())||
                user.getId().equals(message.getPostUserId())){
            log.warn(" 查询了不属于自己的站内信： userId = " + user.getId() +
                    ", receiveUserId = " + message.getReceiveUserId()+
                    ", postUserId= "+message.getPostUserId());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED));
        }
        messageService.updateStateById(id,(byte) 1);
        return AppResult.success();
    }

    @PostMapping("/reply")
    @Operation(summary = "回复站内信")
    public AppResult reply(HttpServletRequest request,
                              @Parameter(name = "repliedId",description = "站内信id")@RequestParam("repliedId")@NotNull Long repliedId,
                              @Parameter(name = "content",description = "回复内容")@RequestParam("content")@NotNull String content){
        Message message = messageService.selectById(repliedId);
        User user = (User) request.getSession(false).getAttribute(AppConfig.USER_SESSION);
        //是否禁言
        if (user.getState()==1){
            log.info(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.fail(ResultCode.FAILED_USER_BANNED);
        }
        if (message==null||
                !user.getId().equals(message.getReceiveUserId())||
                user.getId().equals(message.getPostUserId())){
            log.warn(" 回复了不属于自己的站内信： userId = " + user.getId() +
                    ", receiveUserId = " + message.getReceiveUserId()+
                    ", postUserId= "+message.getPostUserId());
            throw new ApplicationException(AppResult.fail(ResultCode.FAILED));
        }
        messageService.reply(repliedId,content);
        return AppResult.success();
    }

}
